package cn.com.b2office.dao.hibernate;

import java.util.Date;
import java.util.List;

import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import cn.com.b2office.dao.OOSReportDao;
import cn.com.b2office.domain.ExData;
import cn.com.b2office.domain.OOSReport;
import cn.com.b2office.exchange.ClassMapping;

public class OOSReportDaoHibernateImpl extends HibernateDaoSupport implements
		OOSReportDao {

	public int addReport(OOSReport report) {
		Session s = getSession();
		try {
			s.save(report);
			// trigger
			ExData data = new ExData();
			data.setEntity(ClassMapping.getClassCode(OOSReport.class));
			data.setEntityId(String.valueOf(report.getIdno()));
			data.setOperation(ExData.INSERT);
			data.setModifytime(new Date());
			s.save(data);
			s.flush();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return report.getIdno();
	}

	public void deleteReport(int reportId) {
		Session s = getSession();
		try {
			Object o = s.get(OOSReport.class, reportId);
			if (o != null)
				s.delete(o);
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
	}

	@SuppressWarnings("unchecked")
	public List<OOSReport> find(String memberId, int firstResult, int maxResults) {
		List<OOSReport> list = null;
		Session s = getSession();
		try {
			list = s.createQuery("from OOSReport where memberId=:memberId")
					.setString("memberId", memberId)
					.setFirstResult(firstResult).setMaxResults(maxResults)
					.list();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
		return list;
	}

	public OOSReport getReport(int idno) {
		return (OOSReport) getHibernateTemplate().get(OOSReport.class, idno);
	}

	public void updateReport(OOSReport report) {
		Session s = getSession();
		try {
			s.update(report);
			// trigger
			ExData data = new ExData();
			data.setEntity(ClassMapping.getClassCode(OOSReport.class));
			data.setEntityId(String.valueOf(report.getIdno()));
			data.setOperation(ExData.UPDATE);
			data.setModifytime(new Date());
			s.save(data);
			s.flush();
		} catch (RuntimeException e) {
			throw e;
		} finally {
			releaseSession(s);
		}
	}

	@Override
	public int getTotalRecordNumByMember(String memberId) {
		List list = getHibernateTemplate().find(
				"from OOSReport where memberId=?", memberId);
		return list.size();
	}

}
